﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms ;
using System.Data.SQLite;
using DevExpress.XtraEditors;
using Fcdbas.Core.Collections;

namespace Fcdbas.WinUI.Common
{
    public class WinTranslate : Fcdbas.Platform.Interface.ITranslate<Form,DialogResult,MessageBoxButtons,MessageBoxIcon,MessageBoxDefaultButton,IWin32Window>
    {
        private static Hashtable frmTable = new Hashtable();
        private string dbPath = "Data Source=" + Application.StartupPath + "\\Language.db3" + ";PRAGMA journal_mode=WAL;timeout=20";
        public bool isInsert = true;
        private static WinTranslate _Translate;
        public static WinTranslate GetTranslate()
        {
            if (_Translate == null)
                _Translate = new WinTranslate("Fcdbas", "应用系统", "C", "");
            return _Translate;
        }
       // private static List<TOS.Infrastructure.RPT_FIELD_TRAN> RptFieldTranList;
        public WinTranslate(string appName,string msgTitle, string langType,string compCode)
        {
            this.appName = appName;
            this.msgTitle = msgTitle;
            this.langType = langType;
            this.compCode = compCode;

#if DEBUG
 //           dbConnect = new SQLiteConnection(dbPath);
 //           dbConnect.Open();
  //          dbTransation = dbConnect.BeginTransaction();
#endif
        }
       // private static List<TOS.Infrastructure.RPT_FIELD_TRAN> GetRptFieldTran(string Comp_Code)
      //  {
           // TOS.Infrastructure.BasicTableProxy<TOS.Infrastructure.RPT_FIELD_TRAN, TOS.Model.RPT_FIELD_TRAN> basicProxy = new Infrastructure.BasicTableProxy<Infrastructure.RPT_FIELD_TRAN, Model.RPT_FIELD_TRAN>(Comp_Code);
            //return basicProxy.GetBasicTableAllData("RPT_FIELD_TRAN", typeof(List<TOS.Model.RPT_FIELD_TRAN>), typeof(List<TOS.Model.RPT_FIELD_TRAN>).AssemblyQualifiedName);
       // }
        /// <summary>
        /// 翻译报表结果的网格
        /// </summary>
        /// <param name="grid">要翻译的网格</param>
        /// <param name="rptId">报表ID</param>
        public static void TranslateRptGridControl(DevExpress.XtraGrid.GridControl grid,string rptId)
        {
            if (grid == null || grid.MainView == null)
                return;
            DevExpress.XtraGrid.Views.Grid.GridView gview = grid.MainView as DevExpress.XtraGrid.Views.Grid.GridView;
            if (gview == null)
                return;

            string[] ctrlText = new string[gview.Columns.Count];
            
            for (int idx = 0;  idx < gview.Columns.Count ; idx ++)
            {
                if (idx > ctrlText.Length)
                    break;
                string caption = gview.Columns[idx].Caption;
                if (string.IsNullOrWhiteSpace(caption))
                    caption = gview.Columns[idx].FieldName;
                ctrlText[idx] = caption;
                
                
            }
           // XlateRptText(ctrlText,rptId); //翻译字符数组
            for (int i = 0; i < ctrlText.Length; i++)
            {
                if (i > gview.Columns.Count)
                    break;
                gview.Columns[i].Caption = ctrlText[i];
            }
        }
        private string compCode;
        public string CompCode
        {
            get
            {
                return compCode;
            }
            set
            {
                compCode = value;
            }
        }
        private string appName;
        public string AppName
        {
            get
            {
                return appName;
            }
            set
            {
                appName = value;
            }
        }
        private string langType;
        public string LanguageType
        {
            get
            {
                return langType;
            }
            set
            {
                langType = value;
            }
        }
        private string msgTitle = "系统的提示信息";
        public string MsgTitle
        {
            get
            {
                return msgTitle;
            }
            set
            {
                msgTitle = value;
            }
        }
        /// <summary>
        /// 翻译网格
        /// </summary>
        /// <param name="formName"></param>
        /// <param name="grid"></param>
        public void TranslateGridControl(string formName,DevExpress.XtraGrid.GridControl grid)
        {
            if (grid == null || grid.MainView == null)
                return;
            DevExpress.XtraGrid.Views.Grid.GridView gview = grid.MainView as DevExpress.XtraGrid.Views.Grid.GridView;
            if (gview == null)
                return;
#if DEBUG
            dbConnect = new SQLiteConnection(dbPath);
            dbConnect.Open();
            dbTransation = dbConnect.BeginTransaction();
#endif
            string[] ctrlText = new string[gview.Columns.Count];
            
            for (int idx = 0;  idx < gview.Columns.Count ; idx ++)
            {
                if (idx > ctrlText.Length)
                    break;
                string caption = gview.Columns[idx].Caption;
                if (string.IsNullOrWhiteSpace(caption))
                    caption = gview.Columns[idx].FieldName;
                ctrlText[idx] = caption;
                InsertToDb("***", "", caption, caption);
                
            }
#if DEBUG
            CloseDbConnect();
#endif
            XlateText(formName, ctrlText); //翻译字符数组
            for (int i = 0; i < ctrlText.Length; i++)
            {
                if (i > gview.Columns.Count)
                    break;
                gview.Columns[i].Caption = ctrlText[i];
            }
        }
        /// <summary>
		/// 翻译用户控件,
		/// </summary>
		/// <param name="formName"></param>
		/// <param name="userControl"></param>
		public void TranslateControl(string formName,Control userControl)
		{
			Hashtable controls=new Hashtable();

			TraverseControls(userControl,controls);
			string[] ctrlText=new string[controls.Count];
			Control[] ctrls=new Control[controls.Count];

			for(int i=0;i<ctrlText.Length;i++)
			{
				ctrls[i]=(Control)controls["ctrl"+i.ToString()]; //将哈唏表中对应控件赋给控件数组
                InsertToDb(this.appName, formName, ctrls[i].Text, ctrls[i].Text);
				ctrlText[i]=ctrls[i].Text;  //控件数组中某一控件Text属性值赋给字符数组
			}
			XlateText(formName,ctrlText); //翻译字符数组
			for(int i=0;i<ctrlText.Length;i++)
				ctrls[i].Text=ctrlText[i]; //将字符数组对应值赋给控件数组
		}
        
		/// <summary>
		/// 翻译窗体常规控件,将Text属性翻译成相应的语言。最好在窗体的构造函数中使用，防止多次翻译。
		/// </summary>
		/// <param name="formName">窗体名</param>
		/// <param name="frm">窗体对象</param>
		public void TranslateForm(string formName,Form frm)
		{
            TranslateControl(frm, true, formName);
#if DEBUG
            CloseDbConnect();
#endif
		}		
#if DEBUG
        public void CloseDbConnect()
        {
            if (nInsert > 0)
                dbTransation.Commit();
            else
                dbTransation.Rollback();
            dbConnect.Close();
            dbConnect.Dispose();
        }
#endif
		
		/// <summary>
		/// 翻译ListView
		/// </summary>
		/// <param name="formName">窗体名</param>
		/// <param name="listView">ListView对象</param>
		public void TranslateListView(string formName, ListView listView)
		{
			int itemCount=listView.Columns.Count;
			string[] itemText=new string[itemCount];
			for(int i=0;i<itemCount;i++) itemText[i]=listView.Columns[i].Text;
			XlateText(formName,itemText);
			for(int i=0;i<itemCount;i++) listView.Columns[i].Text =itemText[i];
		}

		/// <summary>
		/// 翻译组合框
		/// </summary>
		/// <param name="formName">窗体名</param>
		/// <param name="comboBox">ComboBox对象</param>
		public void TranslateComboBox(string formName, System.Windows.Forms.ComboBox comboBox)
		{
			int itemCount=comboBox.Items.Count;
			string[] itemText=new string[itemCount];
			//翻译Text
			comboBox.Text =XlateWord(formName,comboBox.Text);
			//翻译Item
			for(int i=0;i<itemCount;i++)
			{
				if( comboBox.Items[i].GetType()!=typeof(System.Drawing.Image) | comboBox.Items[i].GetType()!=typeof(System.Drawing.Icon))
					itemText[i] =comboBox.Items[i].ToString();
			}
			XlateText(formName,itemText);
			for(int i=0;i<itemCount;i++)
			{
				if( itemText[i]!="" )
					comboBox.Items[i] =itemText[i];
			}
		}

		

		/// <summary>
		/// 翻译标准的工具栏控件。
		/// </summary>
		/// <param name="formName">窗体名</param>
		/// <param name="toolbar">ToolBar对象</param>
		public void TranslateToolBar(string formName,ToolBar toolbar)
		{
			string[] itemText =new string[toolbar.Buttons.Count];
            string[] itemTipText = new string[toolbar.Buttons.Count];
			for(int i=0;i<itemText.Length;i++)
				itemText[i]=toolbar.Buttons[i].Text;
            for (int i = 0; i < itemText.Length; i++)
                itemTipText[i] = toolbar.Buttons[i].ToolTipText; 
			XlateText(formName,itemText);
            XlateText(formName, itemTipText);
            for (int i = 0; i < itemText.Length; i++)
            {
                //Console.WriteLine(i);
                toolbar.Buttons[i].Text = itemText[i];
                toolbar.Buttons[i].ToolTipText = itemTipText[i];
            }
		}

		/// <summary>
		/// 翻译标准的菜单栏控件。
		/// </summary>
		/// <param name="formName">窗体名</param>
		/// <param name="mainMenu">MainMenu对象</param>
		private  void TranslateMainMenu(string formName,MainMenu mainMenu) 
		{
            if (mainMenu == null)
                return;
			Hashtable controls=new Hashtable();
			
			TraverseControls(mainMenu,controls);

			string[] ctrlText=new string[controls.Count];
			MenuItem[] ctrls=new MenuItem[controls.Count];
			for(int i=0;i<ctrlText.Length;i++)
			{
				ctrls[i]=(MenuItem)controls["ctrl"+i.ToString()];
                InsertToDb(this.appName, formName, ctrls[i].Text, ctrls[i].Text);
				ctrlText[i]=ctrls[i].Text;
			}
			XlateText(formName,ctrlText);
			for(int i=0;i<ctrlText.Length;i++)
				ctrls[i].Text=ctrlText[i];
		}
        /// <summary>
        /// 翻译标准的上下文菜单栏控件。
        /// </summary>
        /// <param name="formName"></param>
        /// <param name="contextMenu"></param>
        public void TranslateContextMenu(string formName, ContextMenu contextMenu)
        {
            Hashtable controls = new Hashtable();
            if(contextMenu.MenuItems.Count == 0)
                return;
            foreach (MenuItem subctrl in contextMenu.MenuItems)
                TraverseControls(subctrl, controls);

            string[] ctrlText = new string[controls.Count];
            MenuItem[] ctrls = new MenuItem[controls.Count];
            for (int i = 0; i < ctrlText.Length; i++)
            {
                ctrls[i] = (MenuItem)controls["ctrl" + i.ToString()];
                ctrlText[i] = ctrls[i].Text;
            }
            XlateText(formName, ctrlText);
            for (int i = 0; i < ctrlText.Length; i++)
                ctrls[i].Text = ctrlText[i];
        }
        protected void TranslateMenuItem(MenuItem mi,string FormName)
        {
            try
            {
                mi.Text = XlateWord(FormName, mi.Text);
                foreach (MenuItem miSub in mi.MenuItems)
                {
                    if (miSub.MenuItems.Count > 0)
                        TranslateMenuItem(miSub,FormName);
                    else
                        miSub.Text = XlateWord(FormName, miSub.Text);
                }
            }
            catch (Exception ex)
            {
                Fcdbas.Core.Log.XTrace.WriteException(ex);
            }
        }
        private void TranslateControl(Control pCtrl,string FormName)
        {
            try
            {
                Control control = pCtrl;
                if (control.ContextMenu != null)
                    foreach (System.Windows.Forms.MenuItem mi in control.ContextMenu.MenuItems)
                        TranslateMenuItem(mi,FormName);
                if (control is UserControl)
                {
                    TranslateControl(FormName, control);
                }else
                if (control is DevExpress.XtraBars.Ribbon.RibbonControl)
                {
                    TranslateRobbon(FormName, control);
                }else
                if (control is ListView)
                {
                    TranslateListView(FormName, control as ListView);
                }else
                if (control is ToolBar)
                {
                    TranslateToolBar(FormName, (ToolBar)control);
                }else
                if (control is DevExpress.XtraEditors.SplitContainerControl)
                {
                    DevExpress.XtraEditors.SplitContainerControl ctrl = control as DevExpress.XtraEditors.SplitContainerControl;
                    TranslateControl(ctrl.Panel1, false, FormName);
                    TranslateControl(ctrl.Panel2, false, FormName);
                }else
                if (control is DevExpress.XtraEditors.GroupControl)
                {
                    TranslateControl(FormName, control);
                }else
                if(control is Control)
                    TranslateControl(FormName, control);
            }
            catch (Exception ex)
            {
                Fcdbas.Core.Log.XTrace.WriteException(ex);
            }
        }
        protected void TranslateControl(Control ctrl, bool isForm,string formName)
        {
            try
            {
                if (isForm)
                {
                    Form frm = ctrl as Form;
                    TranslateComponents(formName, frm);
                    TranslateMainMenu(formName, frm.Menu);
                    if (frm != null)
                    {
                        Hashtable controls = new Hashtable();

                        TraverseControls(frm, controls);
                        string[] ctrlText = new string[controls.Count];
                        Control[] ctrls = new Control[controls.Count];
                        for (int i = 0; i < ctrlText.Length; i++)
                        {
                            ctrls[i] = (Control)controls["ctrl" + i.ToString()];
                            InsertToDb(this.appName, formName, ctrls[i].Text, ctrls[i].Text);
                            ctrlText[i] = ctrls[i].Text;
                        }
                        XlateText(formName, ctrlText);
                        for (int i = 0; i < ctrlText.Length; i++)
                            ctrls[i].Text = ctrlText[i];
                    }
                }
                else
                {
                    TranslateControl(ctrl,formName);
                }
                foreach (Control c in ctrl.Controls)
                {
                    TranslateControl(c,formName);
                    if (c.Controls.Count > 0)
                        TranslateControl(c, false,formName);
                }
            }
            catch (Exception ex)
            {
                Fcdbas.Core.Log.XTrace.WriteException(ex);
            }
        }
		// 遍历菜单控件包含的所有子控件并添加到集合中。
		private void TraverseControls(MainMenu ctrl,Hashtable controls) 
		{
			if (ctrl.MenuItems.Count==0) return;
			foreach(MenuItem subctrl in ctrl.MenuItems)
				TraverseControls(subctrl,controls);
		}

		// 遍历菜单项控件包含的所有子控件并添加到集合中。
		private void TraverseControls(MenuItem ctrl,Hashtable controls)
		{
			controls.Add("ctrl"+controls.Count.ToString(),ctrl);
			if (ctrl.MenuItems.Count==0) return;
            foreach (MenuItem subctrl in ctrl.MenuItems)
            {
                TraverseControls(subctrl, controls);
            }
		}
        private void TranslateRobbon(string formName,Control ctrl)
        {
            if (ctrl is DevExpress.XtraBars.Ribbon.RibbonControl)
            {
                DevExpress.XtraBars.Ribbon.RibbonControl taskbar = ctrl as DevExpress.XtraBars.Ribbon.RibbonControl;
                string[] itemText = new string[taskbar.Items.Count];
                string[] itemTipText = new string[taskbar.Items.Count];
                for (int i = 0; i < taskbar.Items.Count; i++)
                {
                    if (taskbar.Items[i] is DevExpress.XtraBars.BarButtonItem)
                    {
                        itemText[i] = taskbar.Items[i].Caption;
                        InsertToDb(this.appName, formName, taskbar.Items[i].Caption, taskbar.Items[i].Caption);
                        itemTipText[i] = taskbar.Items[i].Hint;
                    }
                }
                XlateText(formName, itemText);
                XlateText(formName, itemTipText);
                for (int i = 0; i < taskbar.Items.Count; i++)
                {
                    if (taskbar.Items[i] is DevExpress.XtraBars.BarButtonItem)
                    {
                        taskbar.Items[i].Caption = itemText[i];
                        taskbar.Items[i].Hint = itemTipText[i];
                    }
                }
            }
        }
        private void TranslateComponents(string formName,Form ctrl)
        {
            if (ctrl is Form)
            {
                List<string> captions = new List<string>();
                List<string> hits = new List<string>();
                Form f = ctrl as Form;
                if (f.Container == null)
                    return;
                for (int i = 0; i < f.Container.Components.Count; i++)
                {
                    if (f.Container.Components[i] is DevExpress.XtraBars.BarManager)
                    {
                        DevExpress.XtraBars.BarManager bm = f.Container.Components[i] as DevExpress.XtraBars.BarManager;
                        for (int j = 0; j < bm.Items.Count; j++)
                        {
                            if (bm.Items[j] is DevExpress.XtraBars.BarButtonItem)
                            {
                                captions.Add(bm.Items[j].Caption);
                                hits.Add(bm.Items[j].Hint);
                                InsertToDb(this.appName, formName, bm.Items[i].Caption, bm.Items[i].Caption);

                            }
                        }
                    }
                }
                string []itemText = captions.ToArray();
                string[] itemHintText = hits.ToArray();
                XlateText(formName, itemText);
                XlateText(formName, itemHintText);
                int idx = 0;
                for (int i = 0; i < f.Container.Components.Count; i++)
                {
                    if (f.Container.Components[i] is DevExpress.XtraBars.BarManager)
                    {
                        DevExpress.XtraBars.BarManager bm = f.Container.Components[i] as DevExpress.XtraBars.BarManager;
                        for (int j = 0; j < bm.Items.Count; j++)
                        {
                            if (bm.Items[j] is DevExpress.XtraBars.BarButtonItem)
                            {
                                if (idx < itemText.Length)
                                {
                                    bm.Items[j].Caption = itemText[idx];
                                    bm.Items[j].Hint = itemHintText[idx];
                                }
                            }
                        }
                    }
                }
            }
            
        }
		/// <summary>
		/// 遍历控件包含的所有子控件并添加到集合中。
		/// </summary>
		/// <param name="ctrl">要遍历的顶层控件</param>
		/// <param name="controls">存放控件引用的集合</param>
		private void TraverseControls(Control ctrl,Hashtable controls)
		{
           
			//文本框及没有标题的控件不用翻译 
			//文本框和下拉框不用翻译
			//if ((ctrl.Text!="")&&!(ctrl is TextBox))
           
			if (!(ctrl is TextBox) && !(ctrl is System.Windows.Forms.ComboBox) && !(ctrl is UserControl) && !(ctrl is TextEdit) 
                && !(ctrl is BaseEdit)  && !(ctrl is MemoEdit) &&!(ctrl is MemoExEdit) && !(ctrl is ComboBoxEdit))
				controls.Add("ctrl"+controls.Count.ToString(),ctrl);
			if (ctrl.Controls.Count==0) return;
			foreach(Control subctrl in ctrl.Controls)
				TraverseControls(subctrl,controls);	
		}
        private void GetfromDB(string sql, Hashtable items)
        {
            using (SQLiteConnection dbConnect = new SQLiteConnection(dbPath))
            {
                SQLiteCommand command = new SQLiteCommand(sql, dbConnect);
                dbConnect.Open();
                SQLiteDataReader reader = command.ExecuteReader();
                while (reader.Read())
                {
                    string key = reader.GetString(1);
                    string value = reader.GetString(2);
                    if (string.IsNullOrEmpty(key) || string.IsNullOrEmpty(value))
                        continue;
                    if (!items.ContainsKey(key.ToLower()))
                        items.Add(key.ToLower(), value);
                }
                reader.Close();
                dbConnect.Close();
            }
        }
#if DEBUG
        private SQLiteConnection dbConnect ;//= new SQLiteConnection(dbPath);
        private SQLiteTransaction dbTransation;
        private int nInsert = 0;
#endif
        private void InsertToDb(string appName,string FormName,string ctrlName,string ctrlText)
        {
#if DEBUG
            if (!isInsert)
                return;
            if (string.IsNullOrEmpty(ctrlName))
                return;
            bool bHas = false;
            string sql = "select FormName FROM LangXlate WHERE AppName='" + appName + "' and ItemName = '" + ctrlName + "' and FormName = '" + FormName + "' and Comp_code ='***'";
            if(string.IsNullOrEmpty(FormName))
                sql = "select FormName FROM LangXlate WHERE AppName='***' and ItemName = '" + ctrlName + "' and Comp_code ='***'";

            return;
          //  using (SQLiteConnection dbConnect = new SQLiteConnection(dbPath))
            {
                SQLiteCommand command = new SQLiteCommand(sql, dbConnect);
            //    dbConnect.Open();
                SQLiteDataReader reader = command.ExecuteReader();
                if (reader.Read())
                {
                    bHas = true;
                }
                reader.Close();
                ///找到，并且不是FromName的词条
                if (appName != "***" && FormName != ctrlName && bHas)
                {
                    sql = "select FormName FROM LangXlate WHERE AppName='***' and ItemName = '" + ctrlName + "' and Comp_code ='***'";
                    command.CommandText = sql;
                    reader = command.ExecuteReader();
                    bool bFound = false;
                    if (reader.Read())
                    {
                        bFound = true;
                    }
                    reader.Close();
                    if (bFound)
                    {
                        sql = "delete from langxlate WHERE AppName='" + appName + "' and ItemName = '" + ctrlName + "' and FormName = '" + FormName + "' and Comp_code ='***'";
                        command.CommandText = sql;
                        command.ExecuteNonQuery();
                        bHas = false;
                        nInsert++;
                    }
                }
                ///没找到,formname 又不为空,找公共的是否已经存在,如果存在，不用增加
                if (!string.IsNullOrEmpty(FormName) && FormName != ctrlName && !bHas)
                {
                    sql = "select FormName FROM LangXlate WHERE AppName='***' and ItemName = '" + ctrlName + "' and Comp_code ='***'";
                    command.CommandText = sql;
                    reader = command.ExecuteReader();
                    
                    if (reader.Read())
                    {
                        bHas = true;
                    }
                    reader.Close();
                }
             //   dbConnect.Close();
            }
            if (!bHas)
            {
              
                string sinsert = @"insert into langxlate(Comp_code,AppName,FormName,ItemName,OthText,CNText) values('***','" + appName +
                    "','" + FormName + "','" + ctrlName + "','" + ctrlText + "','" + ctrlText + "');";
                nInsert++;
                SQLiteCommand insertcommand = new SQLiteCommand(sinsert, dbConnect);
                insertcommand.ExecuteNonQuery();
                
            }
#endif
        }
        /// <summary>
		/// 通用翻译函数，根据ItemName进行翻译。
		/// </summary>
		/// <param name="formName">窗体名</param>
		/// <param name="ctrlText">控件标题数组</param>
		public void XlateText(string formName,string[] ctrlText)
		{
            //未实现
            return;

			//使用哈希表，加快查找速度
			Hashtable items=new Hashtable();
			string[] itemNameArr,rightTextArr,itemNameOldArr;
			bool[] isXlated;
			int ctrlCount;
			string selectText;
			string itemName,rightText;
            string formMaj = CompCode + formName;
			//初始化变量
			ctrlCount=ctrlText.Length;
			itemNameArr=new string[ctrlCount];
			rightTextArr=new string[ctrlCount];
			itemNameOldArr=new string[ctrlCount]; 
			isXlated=new bool[ctrlCount];
			
			for(int i=0;i<ctrlCount;i++)
			{
				if (ctrlText[i]=="") { isXlated[i]=true; continue;}
				SplitCaption(ctrlText[i],out itemName,out rightText);
				itemNameArr[i]=itemName.Trim().ToLower();
				rightTextArr[i]=rightText;
				itemNameOldArr[i]=itemName.Trim(); 
				isXlated[i]=false;
			}
			//翻译
			if (this.langType.ToUpper()=="C")
				selectText="SELECT FormName,ItemName,CNText FROM LangXlate WHERE AppName='" + this.appName + "' and FormName = '" + formName + "' and Comp_code ='" + this.compCode +"'";
			else
                selectText = "SELECT FormName,ItemName,OTHText FROM LangXlate WHERE AppName='" + this.appName + "' and FormName = '" + formName + "' and Comp_code ='" + this.compCode + "'";
            //zh
            if (!string.IsNullOrEmpty(compCode))
            {
                Hashtable mItem = new Hashtable();
                if (!frmTable.ContainsKey(formMaj))
                {

                    GetfromDB(selectText, mItem);
                    frmTable.Add(formMaj, mItem);
                }
                else
                    mItem = frmTable[formMaj] as Hashtable;

                for (int i = 0; i < ctrlCount; i++)
                {
                    if (isXlated[i] || !mItem.ContainsKey(itemNameArr[i])) continue;
                    ctrlText[i] = (string)mItem[itemNameArr[i]] + rightTextArr[i];
                    isXlated[i] = true;
                }
            }
            //zh
            if (!frmTable.ContainsKey(formName))
            {
                //翻译
                if (this.langType == "C")
                    selectText = "SELECT FormName,ItemName,CNText FROM LangXlate WHERE AppName='" + this.appName + "' and FormName = '" + formName + "' and Comp_code ='***'";
                else
                    selectText = "SELECT FormName,ItemName,OTHText FROM LangXlate WHERE AppName='" + this.appName + "' and FormName = '" + formName + "' and Comp_code ='***'";
                GetfromDB(selectText, items);
                frmTable.Add(formName, items);
            }
            else
                items = frmTable[formName] as Hashtable;

			for(int i=0;i<ctrlCount;i++)
			{
				if(isXlated[i]||!items.ContainsKey(itemNameArr[i])) continue;
				ctrlText[i]=(string)items[itemNameArr[i]]+rightTextArr[i];
				isXlated[i]=true;
			}
			//翻译**COMMON
			itemName="";
			for(int i=0;i<ctrlCount;i++)
			{
				if (!isXlated[i]) itemName=itemName+",'"+itemNameArr[i]+"'";
			}
			if (itemName!="")
			{
                if (!string.IsNullOrEmpty(compCode))
                {
                    Hashtable items1 = new Hashtable();
                    if (!frmTable.ContainsKey("***" + compCode))
                    {
                        if (this.langType == "C")
                            selectText = "SELECT FormName,ItemName,CNText FROM LangXlate WHERE AppName='***' and Comp_code ='" + this.compCode + "'";
                        else
                            selectText = "SELECT FormName,ItemName,OTHText WHERE AppName='***' and Comp_code ='" + this.compCode + "'";
                        GetfromDB(selectText, items1);
                        frmTable.Add("***" + compCode, items1);
                    }
                    else
                        items1 = frmTable["***" + compCode] as Hashtable;
                    for (int i = 0; i < ctrlCount; i++)
                    {
                        if (!isXlated[i] && items1.ContainsKey(itemNameArr[i]))
                        {
                            ctrlText[i] = (string)items1[itemNameArr[i]] + rightTextArr[i];
                            isXlated[i] = true;
                        }
                       
                    }
                }
                Hashtable items2 = new Hashtable();
                if (!frmTable.ContainsKey("***"))
                {
                    if (this.langType == "C")
                        selectText = "SELECT FormName,ItemName,CNText FROM LangXlate WHERE AppName='***' and Comp_code ='***'";
                    else
                        selectText = "SELECT FormName,ItemName,OTHText FROM LangXlate WHERE AppName='***' and Comp_code ='***'";
                    GetfromDB(selectText, items2);
                    frmTable.Add("***", items2);
                }
                else
                    items2 = frmTable["***"] as Hashtable;
                for (int i = 0; i < ctrlCount; i++)
                {
                    if (!isXlated[i] && items2.ContainsKey(itemNameArr[i]))
                        ctrlText[i] = (string)items2[itemNameArr[i]] + rightTextArr[i];
                   
                }
               
			}
		}

		/// <summary>
		/// 翻译指定的单词。
		/// </summary>
		/// <param name="formName">窗体名</param>
		/// <param name="word">翻译项目</param>
		/// <returns>对应目标语言的内容</returns>
		public string XlateWord(string formName,string word)
		{
            return word;
            //未实现
            Hashtable items = new Hashtable();
            string selectText;
            if (this.langType.ToUpper() == "C")
                selectText = "ItemName,CNText";
            else
                selectText = "ItemName,OthText";
            string formMaj = this.compCode + formName;
            if (!string.IsNullOrEmpty(this.compCode))
            {
                Hashtable mItem = new Hashtable();
                //翻译
                if (this.langType.ToUpper() == "C")
                    selectText = "SELECT FormName,ItemName,CNText FROM LangXlate WHERE AppName='" + this.appName + "' and FormName = '" + formName + "' and Comp_code ='" + this.compCode + "'";
                else
                    selectText = "SELECT FormName,ItemName,OTHText FROM LangXlate WHERE AppName='" + this.appName + "' and FormName = '" + formName + "' and Comp_code ='" + this.compCode + "'";
                if (!frmTable.ContainsKey(formMaj))
                {
                    GetfromDB(selectText,mItem);
                    //add by zh 
                    frmTable.Add(formMaj, mItem);
                }
                else
                    mItem = frmTable[formMaj] as Hashtable;

                if (mItem.ContainsKey(word.ToLower()))
                    return (string)mItem[word.ToLower()];
            }
            //zh
            if (!frmTable.ContainsKey(formName))
            {
                if (this.langType == "C")
                    selectText = "SELECT FormName,ItemName,CNText FROM LangXlate WHERE AppName='" + this.appName + "' and FormName = '" + formName + "' and Comp_code ='***'";
                else
                    selectText = "SELECT FormName,ItemName,OTHText FROM LangXlate WHERE AppName='" + this.appName + "' and FormName = '" + formName + "' and Comp_code ='***'";
                GetfromDB(selectText, items);
                //add by zh 
                frmTable.Add(formName, items);
            }
            else
                items = frmTable[formName] as Hashtable;

            if (items.ContainsKey(word.ToLower()))
                return (string)items[word.ToLower()];
 
            if (!string.IsNullOrEmpty(compCode))
            {
                Hashtable items1 = new Hashtable();
                if (!frmTable.ContainsKey("***" + compCode ))
                {
                    if (this.langType == "C")
                        selectText = "SELECT FormName,ItemName,CNText  FROM LangXlate WHERE AppName='***' and Comp_code ='" + this.compCode + "'";
                    else
                        selectText = "SELECT FormName,ItemName,OTHText FROM LangXlate WHERE AppName='***' and Comp_code ='" + this.compCode + "'";
                    GetfromDB(selectText, items1);
                    frmTable.Add("***" + compCode, items1);
                }
                else
                    items1 = frmTable["***" + compCode] as Hashtable;
                if (items1.ContainsKey(word.ToLower()))
                    return (string)items1[word.ToLower()];
            }

            Hashtable items2 = new Hashtable();
            if (!frmTable.ContainsKey("***"))
            {

                //items.Clear();
                //baseTable.SelectTable(selectText, "langxlate", "applname='***' and itemname in(" + itemName.Remove(0, 1) + ")", false);
                if (this.langType == "C")
                    selectText = "SELECT FormName,ItemName,CNText FROM LangXlate WHERE AppName='***' and Comp_code ='***'";
                else
                    selectText = "SELECT FormName,ItemName,OTHText FROM LangXlate WHERE AppName='***' and Comp_code ='***'";
                GetfromDB(selectText, items2);
                frmTable.Add("***", items2);
            }
            else
                items2 = frmTable["***"] as Hashtable;
            if (items2.ContainsKey(word.ToLower()))
                return (string)items2[word.ToLower()];
            return word;
		}

		/// <summary>
		/// 将标题按":"分开两部分。
		/// </summary>
		/// <param name="caption">标题</param>
		/// <param name="itemName">ItemName</param>
		/// <param name="rightText">附加文字</param>
		private void SplitCaption(string caption,out string itemName,out string rightText)
		{
            if (caption == null)
                caption = "";
			string[] temp;
			temp=caption.Split(';');
			itemName=temp[0];
			if (temp.Length==1)
				rightText="";
			else
				rightText=" ;"+temp[1];
		}
        private static Hashtable msgHashtable = new Hashtable();
        private void InsertMessage(string msgCode)
        {
#if DEBUG
            bool bHas = false ;
            string sql = "SELECT CnMsg from Message where MsgID=? and comp_code in ('***','" + this.compCode + "');";
            using (SQLiteConnection dbConnect = new SQLiteConnection(dbPath))
            {
                SQLiteCommand command = new SQLiteCommand(sql, dbConnect);
                dbConnect.Open();
                SQLiteParameter param = command.CreateParameter();
                param.DbType = System.Data.DbType.String;
                param.ParameterName = "@MsgID";
                param.Direction = System.Data.ParameterDirection.Input;
                param.Value = msgCode;
                command.Parameters.Add(param);
                SQLiteDataReader reader = command.ExecuteReader();
                if (reader.Read())
                {
                    bHas = true;
                }
                reader.Close();
                dbConnect.Close();
            
                if (!bHas)
                {
                
                    string sqlInsert = @"insert into Message(COMP_CODE,MsgID,CnMsg,OthMsg) values(?,?,?,?);";
                    SQLiteCommand insertcommand = new SQLiteCommand(sqlInsert, dbConnect);
                    dbConnect.Open();
                    insertcommand.Parameters.Add("@Comp_code", System.Data.DbType.String).Value = "***";
                    insertcommand.Parameters.Add("@MsgID1", System.Data.DbType.String).Value = msgCode;
                    insertcommand.Parameters.Add("@MsgID2", System.Data.DbType.String).Value = msgCode;
                    insertcommand.Parameters.Add("@MsgID3", System.Data.DbType.String).Value = msgCode;
                    insertcommand.ExecuteNonQuery();
                    dbConnect.Close();
                }
            }
#endif
        }
        public string XlateMessage(string msgCode, string msgAdd)
        {
           
            //
           // InsertMessage(msgCode);
            char sep = ',';
            string[] paramList;
            string msgText=msgCode;
            if (!string.IsNullOrEmpty(msgAdd))
            {
                msgAdd = msgAdd.Trim();
                if (msgAdd != "")
                {
                    paramList = msgAdd.Split(sep);
                    for (int i = 1; i <= paramList.Length; i++)
                        msgText = msgText.Replace("%%" + i.ToString(), paramList[i - 1]);
                }
            }
            return msgText;
            string sql = "";
            if (!msgHashtable.ContainsKey(msgCode))
            {
                if (this.langType.ToUpper() == "C")
                    sql = "SELECT CnMsg from Message where MsgID=? and comp_code in ('***','" + this.compCode + "');";
                else
                    sql = "SELECT OthMsg from Message where MsgID=? and comp_code in ('***','" + this.compCode + "');";

                using (SQLiteConnection dbConnect = new SQLiteConnection(dbPath))
                {
                    SQLiteCommand command = new SQLiteCommand(sql, dbConnect);
                    SQLiteParameter param= command.CreateParameter();
                    param.ParameterName = "@MsgID";
                    param.DbType = System.Data.DbType.String;
                    param.Direction = System.Data.ParameterDirection.Input;
                    param.Value = msgCode;
                    command.Parameters.Add(param);
                    dbConnect.Open();
                    SQLiteDataReader reader = command.ExecuteReader();
                    while (reader.Read())
                    {
                        msgText = reader.GetString(0);
                    }
                    reader.Close();
                    dbConnect.Close();
                }
                if (msgAdd != "")
                {
                    paramList = msgAdd.Split(sep);
                    for (int i = 1; i <= paramList.Length; i++)
                        msgText = msgText.Replace("%%" + i.ToString(), paramList[i - 1]);
                }
                msgHashtable.Add(msgCode, msgText);
            }
            else
                msgText = msgHashtable[msgCode].ToString();

            if (msgText.Trim() == "")
                msgText = msgCode;

            return msgText;
        }

        /// <summary>
        /// 显示对话框。
        /// </summary>
        /// <param name="msgCode">消息代码</param>
        /// <returns>选择结果</returns>
        public DialogResult ShowMessage(string msgCode)
        {
            string msgText;
            DialogResult result;

            string tranTitle = XlateWord(this.AppName, msgTitle);
            msgText = XlateMessage(msgCode, "").Trim();

            result = XtraMessageBox.Show(msgText, tranTitle);

            return result;
        }

        /// <summary>
        /// 显示对话框。
        /// </summary>
        /// <param name="msgCode">消息代码</param>
        /// <param name="msgAdd">消息参数，多个参数之间用","分开</param>
        /// <returns>选择结果</returns>
        public DialogResult ShowMessage(string msgCode, string msgAdd)
        {
            string msgText;
            DialogResult result;

            string tranTitle = XlateWord(this.AppName, msgTitle);
            msgText = XlateMessage(msgCode, msgAdd);

            result = XtraMessageBox.Show(msgText, tranTitle);

            return result;
        }


        /// <summary>
        /// 显示对话框
        /// </summary>
        /// <param name="msgCode">消息代码</param>
        /// <param name="msgAdd">消息参数，多个参数之间用","分开</param>
        /// <param name="title">标题</param>
        /// <param name="buttonsType">MessageBoxButtons</param>
        /// <returns>选择结果</returns>
        public DialogResult ShowMessage(string msgCode, string msgAdd, string title, MessageBoxButtons buttonsType)
        {
            string msgText;
            DialogResult result;

            string tranTitle = XlateWord(this.AppName, title);
            msgText = XlateMessage(msgCode, msgAdd);

            result = XtraMessageBox.Show(msgText, tranTitle, buttonsType);

            return result;
        }


        /// <summary>
        /// 显示对话框
        /// </summary>
        /// <param name="msgCode">消息代码</param>
        /// <param name="msgAdd">消息参数，多个参数之间用","分开</param>
        /// <param name="title">标题</param>
        /// <param name="buttonsType">MessageBoxButtons</param>
        /// <param name="iconType">MessageBoxIcon</param>
        /// <returns>选择结果</returns>
        public DialogResult ShowMessage(string msgCode, string msgAdd, string title, MessageBoxButtons buttonsType, MessageBoxIcon iconType)
        {
            string msgText;
            DialogResult result;
            if (iconType == MessageBoxIcon.Warning)
                title = "系统的警告";
            else if (iconType == MessageBoxIcon.Error)
                title = "系统的错误";
            else
                title = "系统的提示信息";
            string tranTitle = XlateWord(this.AppName, title);
            msgText = XlateMessage(msgCode, msgAdd);

            result = XtraMessageBox.Show(msgText, tranTitle, buttonsType, iconType);
            return result;
        }

        /// <summary>
        /// 显示对话框
        /// </summary>
        /// <param name="msgCode">消息代码</param>
        /// <param name="msgAdd">消息参数，多个参数之间用","分开</param>
        /// <param name="title">标题</param>
        /// <param name="buttonsType">MessageBoxButtons类型</param>
        /// <param name="iconType">MessageBoxIcon类型</param>
        /// <param name="btn">MessageBoxDefaultButton</param>
        /// <returns>选择结果</returns>
        public DialogResult ShowMessage(string msgCode, string msgAdd, string title, MessageBoxButtons buttonsType, MessageBoxIcon iconType, MessageBoxDefaultButton btn)
        {
            string msgText;
            DialogResult result;
            if (iconType == MessageBoxIcon.Warning)
                title = "系统的警告";
            else if (iconType == MessageBoxIcon.Error)
                title = "系统的错误";
            else
                title = "系统的提示信息";
            string tranTitle = XlateWord(this.AppName, title);
            msgText = XlateMessage(msgCode, msgAdd);

            result = XtraMessageBox.Show(msgText, tranTitle, buttonsType, iconType, btn);
            return result;
        }

        /// <summary>
        /// 显示对话框。
        /// </summary>
        /// <param name="msgCode">消息代码</param>
        /// <param name="msgAdd">消息参数，多个参数之间用","分开</param>
        /// <param name="buttonsType">显示的按钮</param>
        /// <returns>选择结果</returns>
        public DialogResult ShowMessage(string msgCode, string msgAdd, MessageBoxButtons buttonsType)
        {
            string msgText;
            DialogResult result;

            string tranTitle = XlateWord(this.AppName, msgTitle);
            msgText = XlateMessage(msgCode, msgAdd);

            result = XtraMessageBox.Show(msgText, tranTitle, buttonsType);

            return result;
        }

        /// <summary>
        /// 显示对话框。
        /// </summary>
        /// <param name="msgCode">消息代码</param>
        /// <param name="msgAdd">消息参数，多个参数之间用","分开</param>
        /// <param name="buttonsType">显示的按钮</param>
        /// <param name="iconType">图标类型</param>
        /// <returns>选择结果</returns>
        public DialogResult ShowMessage(string msgCode, string msgAdd, MessageBoxButtons buttonsType, MessageBoxIcon iconType)
        {
            string msgText;
            DialogResult result;
            string title = "";
            if (iconType == MessageBoxIcon.Warning)
                title = "系统的警告";
            else if (iconType == MessageBoxIcon.Error)
                title = "系统的错误";
            else
                title = "系统的提示信息";
            string tranTitle = XlateWord(this.AppName, title);
            msgText = XlateMessage(msgCode, msgAdd);

            result = XtraMessageBox.Show(msgText, tranTitle, buttonsType, iconType);

            return result;
        }

        /// <summary>
        /// 显示对话框。
        /// </summary>
        /// <param name="owner">窗体句柄</param>
        /// <param name="msgCode">消息代码</param>
        /// <param name="msgAdd">消息参数，多个参数之间用","分开</param>
        /// <param name="buttonsType">显示的按钮</param>
        /// <param name="iconType">图标类型</param>
        /// <param name="defaultButton">默认的按钮</param>
        /// <returns>选择结果</returns>
        public DialogResult ShowMessage(IWin32Window owner, string msgCode, string msgAdd, MessageBoxButtons buttonsType, MessageBoxIcon iconType, MessageBoxDefaultButton defaultButton)
        {
            string msgText;
            DialogResult result;
            string title = "";
            if (iconType == MessageBoxIcon.Warning)
                title = "系统的警告";
            else if (iconType == MessageBoxIcon.Error)
                title = "系统的错误";
            else
                title = "系统的提示信息";
            string tranTitle = XlateWord(this.AppName, title);
            msgText = XlateMessage(msgCode, msgAdd);

            result = XtraMessageBox.Show(owner, msgText, tranTitle, buttonsType, iconType, defaultButton);

            return result;
        }
       

        /// <summary>
        /// 显示对话框。
        /// </summary>
        /// <param name="msgCode">消息代码</param>
        /// <param name="msgAdd">消息参数，多个参数之间用","分开</param>
        /// <param name="buttonsType">显示的按钮</param>
        /// <param name="iconType">图标类型</param>
        /// <param name="defaultButton">默认的按钮</param>
        /// <returns>选择结果</returns>
        public DialogResult ShowMessage(string msgCode, string msgAdd, MessageBoxButtons buttonsType, MessageBoxIcon iconType, MessageBoxDefaultButton defaultButton)
        {
            string msgText;
            DialogResult result;
            string title = "";
            if (iconType == MessageBoxIcon.Warning)
                title = "系统的警告";
            else if (iconType == MessageBoxIcon.Error)
                title = "系统的错误";
            else
                title = "系统的提示信息";
            string tranTitle = XlateWord(this.AppName, title);
            msgText = XlateMessage(msgCode, msgAdd);

            result = XtraMessageBox.Show(msgText, tranTitle, buttonsType, iconType, defaultButton);

            return result;
        }
    }
}
